//
//  ClubSquareForumDetailViewController.swift
//  77Club
//
//  Created by Apple on 2025/1/7.
//

import UIKit
import ZLPhotoBrowser

private let headerID    = "ClubSquareForumDetailVHeaderView"

class ClubSquareForumDetailViewController: ClubBaseViewController, RaeAnimationProtocol {

    private var navView = ClubDynamicDetailNavView()
    private var bottomView = ClubDynamicDetailBottomView()
    private let commitView = ClubDynamicDetailommitView()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubSquareForumDetailCell.self,ClubDynamicDetailommitCell.self,ClubDynamicDetailCommitEmptyCell.self)
        tableView.register(ClubDynamicDetailHeaderView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.sectionFooterHeight = 0
        tableView.contentInset = UIEdgeInsets.zero
        tableView.sectionHeaderTopPadding = 0
        return tableView
    }()
    private var emptyView = ClubEmptyArticleView()
    
    var postID: String = "" {
        didSet{
            loadData()
        }
    }
    
    var pid = ""
    private var commitPid = ""
    private var commitPuid = ""
    private var commitNewsid = ""
    private var model: ClubGameCommunityDetailModel?
    private var commitData: [ClubGameCommunityDetailCommentModel]?
    var communityModel: ClubGameCommunityModel?
    
    var updateDataBlock: (() -> Void)?
    var likeBlock:(()->())?
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 禁用侧滑手势的代理
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        NotificationCenter.default.post(name: .stopDetailAudioPlayer, object: nil)
        // 恢复默认代理
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            navView
            tableView
            bottomView
            commitView
            emptyView
        }
        
        navView.leading(0).trailing(0).top(0).height(.navi_height)
        tableView.leading(0).trailing(0).top(.navi_height).bottom(.tabBar_height)
        bottomView.leading(0).trailing(0).height(.tabBar_height).bottom(0)
        commitView.leading(0).width(.screenWidth).height(47.0.Scale).bottom(0)
        emptyView.leading(0).width(.screenWidth).height(200.0.Scale).top(.navi_height + 160.0.Scale)
        
        commitView.isHidden = true
        emptyView.isHidden = true
        tableView.isHidden = true
        
        emptyView.titleString = "当前帖子已下架"
        
        tableView.refresh_pull {
            self.loadNewData()
        }
        
        navView.backBlock = {
            self.navigationController?.popViewController(animated: true)
        }
        navView.shareBlock = {
            self.showMoreView()
        }
        navView.userBlock = { uid in
            if uid.count > 0 {
                if let user_id = UserDefaultsManager.getString(forKey: .uid), user_id.count > 0, user_id == uid {
                    let otherVC = ClubMineInfoViewController()
                    self.navigationController?.pushViewController(otherVC, animated: true)
                }else{
                    let otherVC = ClubOtherInfoViewController()
                    otherVC.uid = uid
                    otherVC.isDetailFrom = true
                    self.navigationController?.pushViewController(otherVC, animated: true)
                }
            }            
        }
        bottomView.likeBlock = {
            guard let infoId = self.model?.id else { return }
            self.likeAction(type: "0", id: infoId)
        }
        bottomView.commitBlock = {
            self.showCommitView()
        }
        bottomView.shareBlock = {
            let moreView = ClubForumShareView()
            moreView.copyShareBlock = { type in
                self.shareDetail(type: type)
            }
            self.entryAnimate.animation(show: moreView)
        }
        commitView.sendTextBlock = { content in
            self.sentCommit(text: content)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }

    private func showCommitView(){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            if let is_ban = model?.is_ban, is_ban == 1 {
                "您已被禁言".toast_error
            }else{
                self.bottomView.isHidden = true
                self.commitView.isHidden = false
                self.commitView.commitView.becomeFirstResponder()
            }
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    private func showMoreView(){
        
//        guard let md = self.communityModel else { return }
        guard let postMd = self.model else { return }
        
        if postMd.status != "1" {
            
            let delView = ClubForumShareDelView()
            delView.delBlock = {
                Task{
                    let res = await self.network.request(.delPost(postID: postMd.id))
                    if res.isSuccess {
                        "删除成功".toast_success
                        self.updateDataBlock?()
                        self.navigationController?.popViewController(animated: true)
                    }
                }
            }
            self.entryAnimate.animation(show: delView)
        }else{
           
            let moreView = ClubMoreView()
            var dataArr = [ClubMoreModel]()
            if self.communityModel?.my_role == 1 {
                if postMd.is_best {
                    let mod = ClubMoreModel(title: "取消置顶此帖子",img: "ForumDetail_cancelTop",isRed: false,type: 2)
                    dataArr.append(mod)
                }else{
                    let mod = ClubMoreModel(title: "置顶此帖子",img: "ForumDetail_top",isRed: false,type: 1)
                    dataArr.append(mod)
                }
                if let uid = UserDefaultsManager.getString(forKey: .uid), uid == postMd.uid_des {
                    let delModel = ClubMoreModel(title: "删除此帖子", img: "Home_more_del", isRed: true,type: 4)
                    dataArr.append(delModel)
                }else{
                    let mod = ClubMoreModel(title: "下架此帖子",img: "ForumDetail_down",isRed: false,type: 3)
                    dataArr.append(mod)
                }
                    
                moreView.dataSource = dataArr
            }else if self.communityModel?.my_role == 2 {
                    
                if self.communityModel?.perms?.perm_top == 1 {
                    if postMd.is_best {
                        let mod = ClubMoreModel(title: "取消置顶此帖子",img: "ForumDetail_cancelTop",isRed: false,type: 2)
                        dataArr.append(mod)
                    }else{
                        let mod = ClubMoreModel(title: "置顶此帖子",img: "ForumDetail_top",isRed: false,type: 1)
                        dataArr.append(mod)
                    }
                }
                if self.communityModel?.perms?.perm_off == 1 {
                    if let uid = UserDefaultsManager.getString(forKey: .uid), uid == postMd.uid_des {
                        let delModel = ClubMoreModel(title: "删除此帖子", img: "Home_more_del", isRed: true,type: 4)
                        dataArr.append(delModel)
                    }else{
                        let mod = ClubMoreModel(title: "下架此帖子",img: "ForumDetail_down",isRed: false,type: 3)
                        dataArr.append(mod)
                    }
                }else{
                    if let uid = UserDefaultsManager.getString(forKey: .uid), uid == postMd.uid_des {
                        let delModel = ClubMoreModel(title: "删除此帖子", img: "Home_more_del", isRed: true,type: 4)
                        dataArr.append(delModel)
                    }
                }
                    
                moreView.dataSource = dataArr
            }else{
                moreView.isPost = true
                moreView.uid_des = postMd.uid_des
            }
                
            moreView.reportBlock = {
                if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                    let reportVC = ClubReportViewController()
                    reportVC.dynamicID = postMd.id
                    reportVC.type = "0"
                    reportVC.isShequ = true
                    reportVC.updateDataBlock = {
                        self.navigationController?.popViewController(animated: true)
                    }
                    self.present(reportVC, animated: true)
                }else{
                    //登录
                    self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                }
            }
            moreView.delBlock = {
                Task{
                    let res = await self.network.request(.delPost(postID: postMd.id))
                    if res.isSuccess {
                        "删除成功".toast_success
                        self.updateDataBlock?()
                        self.navigationController?.popViewController(animated: true)
                    }
                }
            }
            moreView.copyShareBlock = { type in
                self.shareDetail(type: type)
            }
            moreView.moreBlock = { type in
                guard var postMd = self.model else { return }
                if type == 3 {
                    //下架
                    Task {
                        let res = await self.network.request(.postUpOrDown(id: postMd.id))
                        if res.isSuccess {
                            self.updateDataBlock?()
                            self.navigationController?.popViewController(animated: true)
                        }
                    }
                }else{
                    Task {
                        let res = await self.network.request(.postTopOrDown(id: postMd.id))
                        if res.isSuccess {
                            postMd.is_best = !postMd.is_best
                            self.model = postMd
                            self.updateDataBlock?()
                        }
                    }
                }
            }
            self.entryAnimate.animation(show: moreView)
        }
    }
}

extension ClubSquareForumDetailViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {

        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if section == 1 {
            if self.commitData?.count ?? 0 > 0 {
                return (self.commitData?.count ?? 0)
            }else{
                return 1
            }
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 1 {
            if self.commitData?.count ?? 0 == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubDynamicDetailCommitEmptyCell", for: indexPath) as! ClubDynamicDetailCommitEmptyCell
                cell.commitBlock = {
                    self.showCommitView()
                }
                return cell
            }else{
                let cell = tableView.dequeueReusableCell(withIdentifier: "ClubDynamicDetailommitCell", for: indexPath) as! ClubDynamicDetailommitCell
                cell.forumModel = self.commitData?[indexPath.row]
//                    cell.likeCommitBlock = { id in
//                        self.likeAction(type: "1", id: id)
//                    }
                cell.showMoreView = { commitID , uid in
                    self.commitShare(commitID: commitID, uid: uid)
                }
                return cell
            }
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubSquareForumDetailCell", for: indexPath) as! ClubSquareForumDetailCell
        cell.model = model
        cell.didSelectImage = { index,images in
            self.selectImage(index: index, images: images)
        }
        cell.popBlock = {
            let detailVC = ClubGameDetailViewController()
            detailVC.gameId = self.pid
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
        cell.jumpToDetail = {postId, uid in
            self.toDetailVC(newId: postId, uid: uid)
        }
        cell.toGameDetailVC = { gid in
            let detailVC = ClubGameDetailViewController()
            detailVC.gameId = gid
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
        cell.toTopicDetailVC = { topicId in
            let detailVC = ClubTopicDetailViewController()
            detailVC.topicId = topicId
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 1 {
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                if let is_ban = model?.is_ban, is_ban == 1 {
                    "您已被禁言".toast_error
                }else{
                    if self.commitData?.count ?? 0 == 0 || indexPath.row == 0{
                        
                        self.bottomView.isHidden = true
                        self.commitView.isHidden = false
                        self.commitView.commitView.becomeFirstResponder()
                    }else{
                        
                        guard let md = self.commitData?[indexPath.row - 1] else { return }
                        self.commitView.commitView.placeHolder = "回复" + md.pet_name
                        self.commitPid = md.id
                        self.commitPuid = md.uid
                        self.bottomView.isHidden = true
                        self.commitView.isHidden = false
                        self.commitView.commitView.becomeFirstResponder()
                    }
                }                
            }else{
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if let commitArray = self.commitData, commitArray.count > 0 && section == 1 {
            let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! ClubDynamicDetailHeaderView
            header.titleString = "(\(commitArray.count))"
            return header
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if let commitArray = self.commitData, commitArray.count > 0 && section == 1 {
            return 44.0.Scale
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 1 && self.commitData?.count ?? 0 > 0 && indexPath.row > 0{
            
            guard let md = self.commitData?[indexPath.row - 1] else { return 0.0 }
            var tableViewH = 0.0
            let arr = md.list
            if arr.count > 0 {
                tableViewH = self.calculateHeight(dataArray: arr)
            }
            let height = md.content.calculateTextHeight(font: 15.font_medium!, width: CGFloat.screenWidth - 104.0.Scale) + 99.0.Scale + tableViewH + 12.0.Scale
            return height
        }else if indexPath.section == 0 {
            guard let md = model else { return UITableView.automaticDimension }
            if md.cellH > 0 {
                var H = 215.0
                let titleH = md.title.calculateTextHeight(font: 16.font_semiBold!, width: CGFloat.screenWidth - 24)
                H = titleH + 12.0.Scale + md.webViewH + 4 + md.cellH + H
                if let games = md.games, games.count > 0 {
                    H = H + 68.0.Scale
                }
                return H
            }
            return UITableView.automaticDimension
        }
        
        return UITableView.automaticDimension
    }
    
    private func calculateHeight(dataArray: [ClubGameCommunityDetailCommentModel]) -> CGFloat{
        
        var height = 0.0
        for md in dataArray {
            height += 32.0.Scale
            let contentH = md.content.calculateTextHeight(font: 15.font_medium!, width: CGFloat.screenWidth - 138.0.Scale) + 34.0
            height += contentH
        }
        return height
    }
}

//MARK: action
extension ClubSquareForumDetailViewController {
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func likeAction(type: String, id: String){
        
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            //点赞
            Task{
                ToastUtil.show()
                let _ = await self.network.request(.likeStrategyPost(pid: id, puid: "", type: type),isShowError: false)
                ToastUtil.dismiss()
                self.loadData()
                "点赞成功".toast_success
                self.likeBlock?()
            }
        }else{
            //登录
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    @objc private func commitSonLike(_ noti: Notification){
        
        if let id = noti.userInfo?["id"] as? String {
            likeAction(type: "1", id: id)
        }
    }
    
    // 键盘消失时调用的方法
    @objc func keyboardWillHide(_ notification: Notification) {
        guard let userInfo = notification.userInfo else { return }

        self.commitView.isHidden = true
        self.bottomView.isHidden = false
    }
    
    private func shareDetail(type: Int) {
        if type == 3 {
            ClubGlobalTool.shared.shareToQQ(title: ClubGlobalTool.shared.postShareTitle, description: self.model?.title ?? "", imageUrl: "https://www.77.top/static/ios_logo.jpg", url: self.model?.share_url ?? "")
        }else if type == 4 {
            "分享口令已复制成功".toast_success
            let shareUrl = self.model?.share_url ?? ""
            UIPasteboard.general.string = shareUrl
        }else{
            ClubGlobalTool.shared.shareToWechat(title: ClubGlobalTool.shared.postShareTitle, des: self.model?.title ?? "", image: "AppIcon".toImage!, shareUrl: self.model?.share_url ?? "", shareType: type)
        }
    }
    
    private func commitShare(commitID: String, uid: String){
        let moreView = ClubGameMoreView()
        moreView.uid_des = uid
        moreView.reportBlock = {
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                let reportVC = ClubReportViewController()
                reportVC.dynamicID = commitID
                reportVC.type = "2"
                self.present(reportVC, animated: true)
            }else{
                //登录
                self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
            }
        }
        moreView.delBlock = {
            Task{
                let res = await self.network.request(.delForumCommit(commitID: commitID))
                if res.isSuccess {
                    "删除成功".toast_success
                    self.loadCommitList()
                }
            }
        }

        self.entryAnimate.animation(show: moreView)
    }
    
    private func toDetailVC(newId: String, uid: String){
        
        if uid != "0" {
            //用户
            let detailVC = ClubSquareForumDetailViewController()
            detailVC.postID = newId
            detailVC.pid = self.pid
//            detailVC.gameModel = self.gameModel
            detailVC.likeBlock = {
                self.loadNewData()
            }
            detailVC.updateDataBlock = {
                self.loadNewData()
            }
            self.navigationController?.pushViewController(detailVC, animated: true)
        }else{
            //官方
            let detailVC = ClubForumDetailViewController()
            detailVC.newId = newId
            detailVC.likeBlock = {
                self.loadNewData()
            }
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
    }
}

//MARK: data
extension ClubSquareForumDetailViewController {
    
    private func loadData(){
        
        ToastUtil.show()
        let netGroup = DispatchGroup()
        let workingQueue = DispatchQueue(label: "GameForumDetail")
        
        netGroup.enter()
        workingQueue.async {
            Task{
                let res = await self.network.request(.strategyPostInfo(newID: self.postID),type: ClubGameCommunityDetailModel.self)
                if res.isSuccess, let model = res.model {
                    self.model = model
                    netGroup.leave()
                }
            }
        }
        netGroup.enter()
        workingQueue.async {
            var user_id = ""
            if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                user_id = uid
            }
            Task{
                let commitRes = await self.network.request(.strategyPostCommitList(newID: self.postID, uid: user_id, sortby: "0"),type: ClubGameCommunityDetailCommentModel.self)
                if commitRes.isSuccess, let models = commitRes.models {
                    self.commitData = models
                    netGroup.leave()
                }
            }
        }
        netGroup.notify(queue: workingQueue) {
            DispatchQueue.main.asyncAfter(deadline: .now()) {
                ToastUtil.dismiss()
                self.tableView.refresh_end()
                self.navView.forumModel = self.model
                self.bottomView.forumModel = self.model
                self.commitPid = self.model?.id ?? ""
                self.commitNewsid = self.model?.id ?? ""
                if self.model?.status == "-1" {
                    self.tableView.isHidden = true
                    self.navView.isRemove = true
                    self.bottomView.isHidden = true
                    self.emptyView.isHidden = false
                }else{
                    self.tableView.isHidden = false
                    self.navView.isRemove = false
                    self.bottomView.isHidden = false
                    self.emptyView.isHidden = true
                }
                self.tableView.reloadData()
            }
            
        }
    }

    private func loadNewData(){
        loadData()
    }
    
    private func loadCommitList(){
        
        var user_id = ""
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            user_id = uid
        }
        Task{
            let commitRes = await self.network.request(.strategyPostCommitList(newID: self.postID, uid: user_id, sortby: "0"),type: ClubGameCommunityDetailCommentModel.self)
            if commitRes.isSuccess, let models = commitRes.models {
                self.commitData = models
                self.tableView.reloadSections(IndexSet(integer: 1), with: .automatic)
            }
        }
    }
  
    
    @objc private func likeSoncommit(_ noti: Notification) {
        
        guard let id = noti.userInfo?["id"] as? String else { return }
        Task{
            ToastUtil.show()
            let _ = await self.network.request(.likeStrategyPost(pid: id, puid: "", type: "1"))
            ToastUtil.dismiss()
            "点赞成功".toast_success
            self.loadCommitList()
        }
    }
    
    private func sentCommit(text: String){
        
//        guard let newsID = model?.id else { return }
        self.commitView.isHidden = true
        self.bottomView.isHidden = false
        self.commitView.commitView.resignFirstResponder()
        Task{
            var type = "0"
            if commitPuid.count > 0 {
                type = "1"
            }
            let res = await self.network.requestSpecialData(.addStrategyCommit(pid: self.commitPid, puid: self.commitPuid, type: type, content: text, news_id: self.commitNewsid), type: RaeNetworkBaseModel.self)
            if res.isSuccess {
                "评论成功".toast_success
                self.commitView.commitView.text = ""
                self.commitPid = self.model?.id ?? ""
                self.commitPuid = ""
                self.loadCommitList()
            }else{
                res.errorMessage?.toast_error
            }
        }
    }
}
